package com.quectel.core.module.devicepatrol.service.impl;


import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.device.dto.DeviceDto;
import com.quectel.core.module.device.service.DeviceService;
import com.quectel.core.module.devicepatrol.dao.DevicePatrolRouteDao;
import com.quectel.core.module.devicepatrol.dto.DevicePatrolRouteDeviceDto;
import com.quectel.core.module.devicepatrol.dto.DevicePatrolRouteDto;
import com.quectel.core.module.devicepatrol.entity.DevicePatrolRouteEntity;
import com.quectel.core.module.devicepatrol.service.DevicePatrolRouteDeviceService;
import com.quectel.core.module.devicepatrol.service.DevicePatrolRouteService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2022/05/07 14:07
 */
@DubboService
public class DevicePatrolRouteServiceImpl implements DevicePatrolRouteService {

    private static final Logger LOGGER = LoggerFactory.getLogger(DevicePatrolRouteServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> DEVICE_PATROL_ROUTE_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "DEVICE_PATROL_ROUTE_CACHE_BY_ID:%d", id);

    @Autowired
    private DevicePatrolRouteDao devicePatrolRouteDao;
    @Autowired
    private DevicePatrolRouteDeviceService devicePatrolRouteDeviceService;

    @Autowired
    private VillageService villageService;
    @Autowired
    private DeviceService deviceService;


    @Override
    public DevicePatrolRouteDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                DEVICE_PATROL_ROUTE_CACHE_BY_ID_FUNC.apply(id),

                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public DevicePatrolRouteDto selectById(Long id) {
        DevicePatrolRouteEntity entity = devicePatrolRouteDao.selectById(id);
        DevicePatrolRouteDto devicePatrolRouteDto = paddingField(CopyUtils.copyObj(entity, DevicePatrolRouteDto.class));

        if (devicePatrolRouteDto != null && devicePatrolRouteDto.getRelatedDeviceNum() != null && devicePatrolRouteDto.getRelatedDeviceNum() > 0) {

            List<DevicePatrolRouteDeviceDto> devicePatrolRouteDeviceDtos = devicePatrolRouteDeviceService.queryListByRouteId(devicePatrolRouteDto.getId());

            if (CollectionUtils.isNotEmpty(devicePatrolRouteDeviceDtos)) {
                List<DeviceDto> associateDeviceDtos = new ArrayList<>();
                //将数据封装返回
                for (DevicePatrolRouteDeviceDto dto : devicePatrolRouteDeviceDtos) {
                    associateDeviceDtos.add(deviceService.selectCacheById(dto.getDeviceId()));
                }
                devicePatrolRouteDto.setRelatedDevices(associateDeviceDtos);
            }
        }

        return devicePatrolRouteDto;
    }

    @Override
    public List<DevicePatrolRouteDto> queryList(Map<String, Object> params) {
        List<DevicePatrolRouteEntity> list = devicePatrolRouteDao.queryList(params);
        List<DevicePatrolRouteDto> result = CopyUtils.copyList(list, DevicePatrolRouteDto.class);
        result.forEach(this::paddingField);
        return result;
    }


    private DevicePatrolRouteDto paddingField(DevicePatrolRouteDto dto) {
        if (dto != null) {
            if (dto.getVillageId() != null) {
                VillageDto villageDto = villageService.selectCacheById(dto.getVillageId());
                dto.setVillageName(villageDto.getName());
            }

            List<DevicePatrolRouteDeviceDto> devicePatrolRouteDeviceDtos = devicePatrolRouteDeviceService.queryListByRouteId(dto.getId());

            if (CollectionUtils.isNotEmpty(devicePatrolRouteDeviceDtos)) {
                dto.setRelatedDeviceNum(devicePatrolRouteDeviceDtos.size());
            } else {
                dto.setRelatedDeviceNum(0);
            }
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return devicePatrolRouteDao.queryTotal(params);
    }

    @Override
    public Long save(DevicePatrolRouteDto dto) {
        DevicePatrolRouteEntity entity = CopyUtils.copyObj(dto, DevicePatrolRouteEntity.class);
        entity.setId(Snowflake.nextId());
        devicePatrolRouteDao.insert(entity);
        return entity.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(DevicePatrolRouteDto dto) {
        DevicePatrolRouteEntity entity = CopyUtils.copyObj(dto, DevicePatrolRouteEntity.class);
        devicePatrolRouteDao.updateById(entity);
        updateDevicePatrolRouteDevice(dto);
        CacheKit.invalidRedisCache(DEVICE_PATROL_ROUTE_CACHE_BY_ID_FUNC.apply(dto.getId()));
    }

    private void updateDevicePatrolRouteDevice(DevicePatrolRouteDto dto) {
        //第一步 清除关系
        devicePatrolRouteDeviceService.deleteByRouteId(dto.getId());
        if (CollectionUtils.isNotEmpty(dto.getDevicePatrolRouteDeviceDtos())) {
            //第二步 保存关系
            for (DevicePatrolRouteDeviceDto devicePatrolRouteDeviceDto : dto.getDevicePatrolRouteDeviceDtos()) {
                devicePatrolRouteDeviceDto.setRouteId(dto.getId());
                devicePatrolRouteDeviceService.save(devicePatrolRouteDeviceDto);
            }
        }
    }

    @Override
    public void updateAllColumnById(DevicePatrolRouteDto dto) {
        DevicePatrolRouteEntity entity = CopyUtils.copyObj(dto, DevicePatrolRouteEntity.class);


        MyBatisPlusUtils.updateAllColumnById(entity, devicePatrolRouteDao);

        CacheKit.invalidRedisCache(DEVICE_PATROL_ROUTE_CACHE_BY_ID_FUNC.apply(dto.getId()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Long id) {
        devicePatrolRouteDao.deleteById(id);
        devicePatrolRouteDeviceService.deleteByRouteId(id);
        CacheKit.invalidRedisCache(DEVICE_PATROL_ROUTE_CACHE_BY_ID_FUNC.apply(id));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
